package com.example.todotask.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.todotask.model.DaoMaster;
import com.example.todotask.model.DaoMaster.DevOpenHelper;
import com.example.todotask.model.DaoSession;
import com.example.todotask.model.TaskDao;

public class DatabaseHandler {

	public static final String DB_NAME = "task-db";
	private static SQLiteDatabase db;
	private static DaoMaster daoMaster;
	private static DaoSession daoSession;
	private static TaskDao taskDao;

	public DatabaseHandler(Context context) {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		
		taskDao = daoSession.getTaskDao();
	}
	
	/**
	 * Get Id last task Id. 
	 */
	public long getNextID() {
		String query = "SELECT MAX(_id) FROM " + TaskDao.TABLENAME;
		Cursor cursor = db.rawQuery(query, null);
		if (cursor.moveToFirst()) {
			long i =cursor.getLong(0) + 1;
			cursor.close();
			return i;
		} else {
			cursor.close();
			return 1;
		}
	}
	
	public SQLiteDatabase getDb() {
		return db;
	}
	
	public TaskDao getTaskDao() {
		return taskDao;
	}
	
	public static void close() {
		db.close();
	}
}
